/**
 * 
 */
package com.gmail.blackdog1987.carcare.activity;

import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.gmail.blackdog1987.carcare.App;
import com.gmail.blackdog1987.carcare.BaseFragmentActivity;
import com.gmail.blackdog1987.carcare.Constant.Config;
import com.gmail.blackdog1987.carcare.R;
import com.gmail.blackdog1987.carcare.adapter.TabsAdapter;
import com.gmail.blackdog1987.carcare.entity.TConfig;
import com.gmail.blackdog1987.carcare.entity.TGasConfig;
import com.gmail.blackdog1987.carcare.fragment.AccountFragment;
import com.gmail.blackdog1987.carcare.fragment.HomeFragment;
import com.gmail.blackdog1987.carcare.fragment.PromotionFragment;
import com.gmail.blackdog1987.carcare.fragment.SettingFragment;
import com.gmail.blackdog1987.carcare.network.request.builder.ConfigRequestBuilder;
import com.gmail.blackdog1987.carcare.network.request.builder.GasGetConfigRequestBuilder;
import com.gmail.blackdog1987.carcare.network.response.ConfigResponse;
import com.gmail.blackdog1987.carcare.network.response.GasGetConfigResponse;
import com.gmail.blackdog1987.carcare.network.response.IResponse;
import com.gmail.blackdog1987.carcare.network.response.handler.ConfigResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.GasGetConfigResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.IResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.OnResponseListener;
import com.gmail.blackdog1987.carcare.util.DoubleTapDetector;
import com.gmail.blackdog1987.carcare.util.DoubleTapDetector.DoubleTapListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

/**
 * @author wdy
 * 
 */
public class LaunchActivity extends BaseFragmentActivity implements OnClickListener, DoubleTapListener, OnResponseListener {
	private Context mContext;
	/** 双击感应器 */
	private DoubleTapDetector mDoubleClickDetector;

	private TabHost mTabHost;
	private ViewPager mViewPager;
	private static TabsAdapter mTabsAdapter;

	private TabStruct[] mTabStructs;
	GasGetConfigRequestBuilder mReq = new GasGetConfigRequestBuilder();
	GasGetConfigResponseHandler mHandler = new GasGetConfigResponseHandler();
	
	ConfigRequestBuilder mConfigReq = new ConfigRequestBuilder();
	ConfigResponseHandler mConfigHandler = new ConfigResponseHandler();
	
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	
	private void update() {
		UmengUpdateAgent.setUpdateAutoPopup(false);
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
			@Override
			public void onUpdateReturned(int updateStatus,
					UpdateResponse updateInfo) {
				switch (updateStatus) {
				case UpdateStatus.Yes: // has update
					UmengUpdateAgent.showUpdateDialog(mContext, updateInfo);
					break;
				case UpdateStatus.No: // has no update
					// Toast.makeText(mContext, "没有更新",
					// Toast.LENGTH_SHORT).show();
					break;
				case UpdateStatus.NoneWifi: // none wifi
					// Toast.makeText(mContext, "没有wifi连接， 只在wifi下更新",
					// Toast.LENGTH_SHORT).show();
					break;
				case UpdateStatus.Timeout: // time out
					// Toast.makeText(mContext, "超时",
					// Toast.LENGTH_SHORT).show();
					break;
				}
			}
		});
		UmengUpdateAgent.update(this);
	}

	public void initViews() {

	}

	public void reg() {
	}

	public void initData(Bundle savedInstanceState) {
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		default:
			break;
		}

	}

	/**
	 * 获取Tab的Tag。
	 * 
	 * @param index
	 *            索引。
	 * @return Tab的Tag。
	 */
	public String getTabTag(int index) {
		return mTabStructs[index].mTag;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_launch);
		mContext = this;
		mHandler.setOnResponseListener(this);
		mConfigHandler.setOnResponseListener(this);
		mReq.postJsonRequest(mContext, mHandler);
		mConfigReq.postJsonRequest(mContext, mConfigHandler);
		initViews();
		initData(savedInstanceState);
		reg();
		update();
		
		mDoubleClickDetector = new DoubleTapDetector(this, this, "再次点击返回退出应用");

		// --------------------------------------------------
		// 创建tab页
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		mViewPager = (ViewPager) findViewById(R.id.pager);

		String[] texts = getResources().getStringArray(R.array.tab_text_array);

		mTabStructs = new TabStruct[] { new TabStruct("main", texts[3], R.drawable.ic_tab_main, R.drawable.ic_tab_main_press, HomeFragment.class),
				new TabStruct("collection", texts[2], R.drawable.ic_tab_collection, R.drawable.ic_tab_collection_press, PromotionFragment.class),
				new TabStruct("setting", texts[0], R.drawable.ic_tab_me, R.drawable.ic_tab_me_press, AccountFragment.class),
				new TabStruct("me", texts[1], R.drawable.ic_tab_setting, R.drawable.ic_tab_setting_press, SettingFragment.class) };

		mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
		for (TabStruct struct : mTabStructs) {
			mTabsAdapter.addTab(mTabHost.newTabSpec(struct.mTag).setIndicator(struct.mView), struct.mClss, null);
		}

		// 设置tab页动画
		mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				showTab(tabId);
			}
		});
		showTab(mTabStructs[0].mTag);
		
		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
		} else {
			mTabHost.setCurrentTab(0);
		}
		
		// 定位
		mLocClient = new LocationClient(LaunchActivity.this);
		mLocClient.registerLocationListener(myListener);
		final LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps

		option.setCoorType("bd09ll"); // 设置坐标类型

		option.setScanSpan(1000);

		mLocClient.setLocOption(option);
		mLocClient.start();
		
//		Intent i = new Intent(LaunchActivity.this,WelcomeActivity.class); 
//		startActivity(i); 
//		overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
	}
	
	/**
	 * 动画显示tab
	 * 
	 * @param tabTag
	 *            tab标记
	 */
	public void showTab(String tabTag) {
		for (int i = 0; i < mTabStructs.length; i++) {
			View layoutBack = mTabStructs[i].mView.findViewById(R.id.back);
			View layoutFront = mTabStructs[i].mView.findViewById(R.id.front);

			layoutFront.setVisibility(View.VISIBLE);
			if (mTabStructs[i].mTag.equals(tabTag)) {
				mTabStructs[i].mView.setTag(true);
				layoutBack.startAnimation(AnimationUtils.loadAnimation(this, R.anim.tab_exit));
				layoutFront.startAnimation(AnimationUtils.loadAnimation(this, R.anim.tab_enter));
				mViewPager.setCurrentItem(i, true);

			} else if (mTabStructs[i].mView.getTag() != null) {
				mTabStructs[i].mView.setTag(null);
				layoutBack.startAnimation(AnimationUtils.loadAnimation(this, R.anim.tab_enter));
				layoutFront.startAnimation(AnimationUtils.loadAnimation(this, R.anim.tab_exit));

			} else {
				layoutBack.setAnimation(null);
				layoutFront.setAnimation(null);
				layoutFront.setVisibility(View.GONE);
			}
		}
	}
	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Tab特征结构体。
	 */
	private class TabStruct {
		private String mTag;
		private Class<?> mClss;
		private View mView;

		private TabStruct(String tag, String text, int backIconResId, int frontIconResId, Class<?> clss) {
			mTag = tag;
			mClss = clss;
			mView = LayoutInflater.from(LaunchActivity.this).inflate(R.layout.tab_widget, null);

			((ImageView) mView.findViewById(R.id.back_icon)).setImageResource(backIconResId);
			((ImageView) mView.findViewById(R.id.front_icon)).setImageResource(frontIconResId);
			TextView backText = ((TextView) mView.findViewById(R.id.back_text));
			TextView frontText = ((TextView) mView.findViewById(R.id.front_text));
			if (TextUtils.isEmpty(text)) {
				backText.setVisibility(View.GONE);
				frontText.setVisibility(View.GONE);
			} else {
				backText.setText(text);
				frontText.setText(text);
				backText.setVisibility(View.VISIBLE);
				frontText.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public void onBackPressed() {
		mDoubleClickDetector.onKey(KeyEvent.KEYCODE_BACK, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
	}

	@Override
	public void doubleTap() {
		if(isFinishing()){
			
		}else{
			finish();
		}
	}

	@Override
	public void onResponse(IResponseHandler classz) {
		IResponse res = classz.getResponse();
		if(res instanceof GasGetConfigResponse){
			List<TGasConfig> configs = ((GasGetConfigResponse) res).configs;
			for (TGasConfig tGasConfig : configs) {
				if(tGasConfig.getKey().equals("gas_price")){
					try {
						JSONObject json = new JSONObject(tGasConfig.getValue());
						App.GAS_PRICE_MAP.put(Config.GAS_90, json.optString(Config.GAS_90));
						App.GAS_PRICE_MAP.put(Config.GAS_93, json.optString(Config.GAS_93));
						App.GAS_PRICE_MAP.put(Config.GAS_97, json.optString(Config.GAS_97));
						App.GAS_PRICE_MAP.put(Config.GAS_0, json.optString(Config.GAS_0));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				if(tGasConfig.getKey().equals("charge_values")){
					try {
						JSONObject json = new JSONObject(tGasConfig.getValue());
						App.CHARGE_VALUE_MAP.put("create", Arrays.asList(json.optString("create").split(",")));
						App.CHARGE_VALUE_MAP.put("charge", Arrays.asList(json.optString("charge").split(",")));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}else if(res instanceof ConfigResponse){
			List<TConfig> configs = ((ConfigResponse) res).configs;
			for (TConfig config : configs) {
				if(config.getKey().equals("function")){
					try {
						JSONObject json = new JSONObject(config.getValue());
						App.FUNCTION_CONFIG.put(Config.FUNCTION_CARCHANGE, json.optInt(Config.FUNCTION_CARCHANGE, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_CARFIX, json.optInt(Config.FUNCTION_CARFIX, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_CARRENT, json.optInt(Config.FUNCTION_CARRENT, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_CARSALE, json.optInt(Config.FUNCTION_CARSALE, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_CHECK, json.optInt(Config.FUNCTION_CHECK, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_CLEAN, json.optInt(Config.FUNCTION_CLEAN, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_DRIVECOMPANY, json.optInt(Config.FUNCTION_DRIVECOMPANY, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_GAS, json.optInt(Config.FUNCTION_GAS, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_LICENSE, json.optInt(Config.FUNCTION_LICENSE, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_MAINTAIN, json.optInt(Config.FUNCTION_MAINTAIN, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_ROADHELP, json.optInt(Config.FUNCTION_ROADHELP, 0));
						App.FUNCTION_CONFIG.put(Config.FUNCTION_TRAVEL, json.optInt(Config.FUNCTION_TRAVEL, 0));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else if(config.getKey().equals("price")){
					try {
						JSONObject json = new JSONObject(config.getValue());
						App.PRICE_CONFIG.put(Config.FUNCTION_CARCHANGE, json.optInt(Config.FUNCTION_CARCHANGE, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_CARFIX, json.optInt(Config.FUNCTION_CARFIX, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_CARRENT, json.optInt(Config.FUNCTION_CARRENT, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_CARSALE, json.optInt(Config.FUNCTION_CARSALE, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_CHECK, json.optInt(Config.FUNCTION_CHECK, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_CLEAN, json.optInt(Config.FUNCTION_CLEAN, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_DRIVECOMPANY, json.optInt(Config.FUNCTION_DRIVECOMPANY, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_GAS, json.optInt(Config.FUNCTION_GAS, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_LICENSE, json.optInt(Config.FUNCTION_LICENSE, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_MAINTAIN, json.optInt(Config.FUNCTION_MAINTAIN, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_ROADHELP, json.optInt(Config.FUNCTION_ROADHELP, 0));
						App.PRICE_CONFIG.put(Config.FUNCTION_TRAVEL, json.optInt(Config.FUNCTION_TRAVEL, 0));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@Override
	public void onError(IResponseHandler classz) {
		IResponse res = classz.getResponse();
		if(res instanceof GasGetConfigResponse){
			
		}
	}
	
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			App.location = location;
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}
}
